//用户相关的小仓库
import { defineStore } from 'pinia'
//引入类型
import type {
  loginFormData,
  loginResponseData,
  userInfoResponseData,
} from '@/apis/user/type'
import type { userState } from './types/types'
//引入登录网络模块
import { reqLogin, reqUserInfo, reqLogout } from '@/apis/user/index'
//引入本地存储token方法
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token.ts'
//引入路由
import { constantRoute, asyncRoutes, anyRoutes } from '@/router/routes'
import router from '@/router'
//引入深拷贝方法
//@ts-ignore
import cloneDeep from 'lodash/cloneDeep'

//过滤路由的函数
const filterAsyncRoute = (asyncRoute: any, routes: any) => {
  return asyncRoute.filter((item: any) => {
    if (routes.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        item.children = filterAsyncRoute(item.children, routes)
      }

      return true
    }
  })
}

//创建小仓库
let useUserStore = defineStore('User', {
  //仓库存储的地方
  state: (): userState => {
    return {
      token: GET_TOKEN(),
      menuRoutes: constantRoute,
      username: '',
      avatar: '',
      buttons: [], //存储当前用户是否包含某一个按钮
    }
  },
  actions: {
    //用户登录的方法
    async userLogin(data: loginFormData) {
      //登录请求
      const result: loginResponseData = await reqLogin(data)

      //登录请求:成功200->token
      //登录请求:失败201->登录失败错误的信息
      if (result.code == 200) {
        //pinia仓库存储一下token
        //由于pinia|vuex存储数据其实利用js对象
        this.token = result.data as string
        //本地存储持久化存储一份
        SET_TOKEN(result.data as string)
        //能保证当前async函数返回一个成功的promise
        return 'ok'
      } else {
        return Promise.reject(result.data)
      }
    },

    //获取用户信息方法
    async userInfo() {
      //获取用户信息进行存储仓库当中[用户头像、名字]
      const result: userInfoResponseData = await reqUserInfo()
      // console.log(result.data.routes, '用户信息');

      //如果获取用户信息成功，存储一下用户信息
      if (result.code == 200) {
        this.username = result.data.name
        this.avatar = result.data.avatar
        this.buttons = result.data.buttons
        //对比筛选路由数组,计算当前用户展示路由
        //只是菜单需要的数据，并未注册到路由组件里
        let userAsyncRoute = filterAsyncRoute(
          cloneDeep(asyncRoutes),
          result.data.routes,
        )
        // console.log(router.getRoutes())
        //重新组合总共路由
        this.menuRoutes = [...constantRoute, ...userAsyncRoute, ...anyRoutes]
        //  console.log(this.menuRoutes);//目前里面是常量路由
        //动态追加路由
        ;[...anyRoutes, ...userAsyncRoute].forEach((item: any) => {
          router.addRoute(item)
        })
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },

    //退出登录
    async userLogout() {
      //退出登录请求
      const result: any = await reqLogout()
      // console.log(result, '退出')
      //退出登录请求成功
      if (result.code == 200) {
        //目前没有mock接口:退出登录接口(通知服务器本地用户唯一标识失效)
        this.token = ''
        this.username = ''
        this.avatar = ''
        REMOVE_TOKEN()
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
  },
})

export default useUserStore

/*
{
  let token = GET_TOKEN()
  let username = ref('请登录')
  let avatar = ref('')

  const userLogin = async (data: loginForm) => {
    const res: loginResponseData = await reqLogin(data)

    if (res.code === 200) {
      //本地化存储
      token = res.data.token as string
      SET_TOKEN(token)
      return Promise.resolve('ok')
    } else {
      return Promise.reject(res.data.message as string)
    }
  }

  //获取用户信息的方法
  const userInfo = async () => {
    let result = await reqUserInfo()
    if (result.code === 200) {
      username.value = result.data.checkUser.username
      avatar.value = result.data.checkUser.avatar
      return 'ok'
    } else {
      return Promise.reject('获取用户信息失败')
    }

    // return result.data.checkUser
  }

  const userLogout = () => {
    ; (token = ''), (username.value = ''), (avatar.value = '')
    REMOVE_TOKEN()
  }

  const menuRoutes = constantRoute //菜单路由

  return {
    token,
    userLogin,
    menuRoutes,
    userInfo,
    username,
    avatar,
    userLogout,
  }
}
*/
